package ua.org.extjsbuilder.parser.runtime;

import java.io.IOException;
import java.io.Reader;

import ua.org.extjsbuilder.parser.IToken;

public class UnparsedToken extends AbstractToken 
		implements IToken,CharSequence {
	private static final int BUFFER_SIZE = 1024;
	
	public UnparsedToken(Reader reader) throws IOException {
		super(readToken(reader),0);
	}
	
	private UnparsedToken(char[] token,int line){
		super(token,line);
	}

	public UnparsedToken(char[] data, int start, int end, int line) {
		super(arrayCopy(data,start,end-start),line);
	}
	
	private static char[] arrayCopy(char[] data, int start, int len){
		if(len==0)return new char[0];
		if(len<0||start>=data.length||start+len>data.length){
			throw new IndexOutOfBoundsException("arrayCopy(char["+
					data.length+", "+start+", "+len+")");
		}
		char[] tmp = new char[len];
		System.arraycopy(data, start, tmp, 0,len);
		return tmp;
	}

	private static char[] readToken(Reader reader) throws IOException {
		char[] cBuf = new char[BUFFER_SIZE];
		char[] result = new char[0];
		int bufLen = 0;
		while((bufLen=reader.read(cBuf))>0){
			char[] tmp = new char[result.length+bufLen];
			System.arraycopy(result,0,tmp,0, result.length);
			System.arraycopy(cBuf,0,tmp,result.length,bufLen);
			result = tmp;
		}
		return result;
	}

	public char charAt(int index) {
		return token[index];
	}

	public int length() {
		return token.length;
	}

	public CharSequence subSequence(int start, int end) {
		if(end<start||start<0||end>token.length){
			throw new IndexOutOfBoundsException("subSequence("+start+","+end+
					") for token with length "+token.length);
		}
		char[] tmp = new char[end-start];
		System.arraycopy(token,start,tmp,0,tmp.length);
		
		return new UnparsedToken(tmp,line);
	}
	
	public char[] getData(){
		return token;
	}
}
